package org.example.sword2offer.primary;

/**
 * @author: lynn
 * @Descript: leetcode 92   反转区间链表 II
 * @date: 2021/7/8 19:17
 * @version: 1.0
 */
public class Q79_1_ReverseNodeBetweenMN {

    //fixme answer https://www.bilibili.com/video/BV1pA411q7kt?from=search&seid=13730969987270906820
    public ListNode reverseBetween(ListNode head, int left, int right) {
        if (head==null||head.next==null) return head;
        ListNode dummyNode=new ListNode(0);
        dummyNode.next=head;
        ListNode p1=dummyNode;

        while (right>0 && p1!=null){
            right--;
            p1=p1.next;
        }
        ListNode thirdPart=p1.next;
        p1.next=null;
        ListNode p2=dummyNode;
        while (left>0&&p2!=null){
            left--;
            p2=p2.next;
        }

        ListNode secondPart=p2;
        ListNode pre=null;
        while(secondPart!=null){
            ListNode tmp=secondPart.next;
            secondPart.next=pre;
            pre=secondPart;
            secondPart=tmp;
        }
        ListNode p=head;
        ListNode res=p;
        while (p.next!=null && p.next.next!=null){
            p=p.next;
        }
        p.next=pre;
        while (p.next!=null){
            p=p.next;
        }

        p.next=thirdPart;
        return head;
    }
    private static class ListNode{
        ListNode next;
        int val;
        ListNode(int val){
            this.val=val;
        }
    }
    public static void main(String[] args) {
        ListNode node=new ListNode(1);
        node.next=new ListNode(2);
        /*node.next.next=new ListNode(3);
        node.next.next.next=new ListNode(4);
        node.next.next.next.next=new ListNode(5);*/
        Q79_1_ReverseNodeBetweenMN reverseNodeBetweenMN=new Q79_1_ReverseNodeBetweenMN();
        System.out.println(reverseNodeBetweenMN.reverseBetween(node,1,1));
    }
}
